<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends MX_Controller {
 	function __construct()
 	{
    	parent::__construct();
	 	$this->load->model('user/admin_user_model');
	 }
	 
 	function index()
 	{
		$data = array();
		$data['errors'] = '';			
	 	if($this->session->userdata('user_id'))
		{			
			redirect(site_url("admin/landing"));
		}
		 //Lay thong tin remember
        $ssv_uid = trim(get_cookie('ssv_uid'));
        $ssv_pas = trim(get_cookie('ssv_pas'));
                
		$username = $this->input->post('username', TRUE);
		$password = $this->input->post('password');
		$back = $this->input->get('back');
		if($username && $password) {			
			$result = $this->admin_user_model->login($username, $password);					
			if (!empty($result)) {
				$sess_array = array();				
				$this->session->set_userdata($sess_array);		
                $this->session->set_userdata('user_id', $result['id']);
                $this->session->set_userdata('username', $result['username']);
                $this->session->set_userdata('permission', $result['permission']);                                     
                $this->session->set_userdata('last_login', $result['last_login']);				
				if ((int) $this->input->post('remember', true) == 1 || ($ssv_uid != '' && $ssv_pas != '')) {
                	set_cookie('uid', $username, 60 * 60 * 24 * 3, '', '/', 'ssv_', true);
                	set_cookie('pas', $password, 60 * 60 * 24 * 3, '', '/', 'ssv_', true);
                }
                //Update login date
                $user_data = array('id'=>(int) $result['id'],
                					'last_login'=>date("Y-m-d H:i:s")
                					);
               	$this->admin_user_model->update_user($user_data);
				if($back) {
					$backlink = urldecode($back); 
					redirect($backlink);
				} else {
					redirect(site_url('admin/landing'));	
				}
			}	
			$data['errors'] = 'TÃ i khoáº£n hoáº·c máº­t kháº©u chÆ°a chÃ­nh xÃ¡c, vui lÃ²ng thá»­ láº¡i !';
		}
   	 	$this->load->view('login/login_view', $data);
 	} 
	
	public function logout()
	{
		$this->session->unset_userdata('user_id');
        $this->session->unset_userdata('username');
        $this->session->unset_userdata('permission');                
        $this->session->unset_userdata('last_login');
		redirect(site_url('admin/login'));
	}
}
?>
